from django.shortcuts import render
from . import models
from django.http import Http404, HttpResponse, HttpResponseRedirect
import os
# from mysite4 import settings # 不推荐这样导入配置文件
from django.conf import settings # 官方推荐
from django.contrib.auth.models import User as Users# 使用官方用户模板




def hone_view(res):
    """主页"""
    if res.method == 'GET':
        return render(res, 'home/index.html')
    return HttpResponse("鸭儿了嘿.")

def upload_view(res):
    if res.method == 'GET':
        return render(res, 'home/upload.html')
    elif res.method == 'POST':
        a_file = res.FILES['files']
        print(f"上传的文件是: {a_file.name}")
        
        filename = os.path.join(settings.MEDIA_ROOT, a_file.name) # 拼接文件的路径
        print(filename)
        # 文件操作
        try:
            with open(filename, 'wb') as f:
                data = a_file.file.read() # 读取文件流
                f.write(data) # 写入
                # return HttpResponse(f"上传{a_file.name}文件成功.")
                info = f"上传 {a_file.name} 文件成功."
                return render(res, 'home/upload.html', locals())
        except Exception as e:
            info = f"打开失败."
            return render(res, 'home/upload.html', locals())
    raise Http404

# Create your views here.
def login_view(res):
    """登录, 使用Django自带的模板验证账户密码, 一旦使用这个模板, 一些App的数据库验证账户时,会出现数据错误,需要更改"""
    if res.method == 'GET':
        # 如果浏览器中cookie里面的值, 有保存用户名的话,则返回到浏览器中, 这个功能也能用于用户注册成功时返回登录界面,回填到登录框的用户名上
        username = res.COOKIES.get('username', '缺省值(默认)')
        return render(res, 'home/login.html', locals())
    elif res.method == 'POST':
        # 设置cookie中的session的值,用于浏览器保持登录状态
        # 初始化session在服务器的值, 那个浏览器访问服务器就在服务器中的session开辟单独的空间存储关键数据
        # res.session['abc'] = 123 
        
        # 验证用户密码是否为空
        username = res.POST.get('username')
        passwords = res.POST.get('passwd')
        # remember = res.POST.get('remember')
        if username == '':
            error = "用户名不能为空!"
            return render(res, 'home/login.html', locals())
        elif passwords == '':
            error = "密码不能为空!"
            return render(res, 'home/login.html', locals())
        # 验证用户密码
        try:
            # auser = models.User.objects.get(name=username, password=passwords) # 验证自己写的表
            auser = Users.objects.get(username=username) # 验证Django自带的表, 不能同时写上密码验证,因为加密过的密码无法与登录密码一样
            # 使用Django模板验证密码
            if auser.check_password(passwords):
            
                # 如果查询数据对比成功则记录在服务器中的session中, 默认保存时间为2周
                # 如果浏览器请求中有这一项,可以认为用户已经登录过了, 如果没有这个['user']键,则表明没有登录过, 当然['user']中的键名字随便取
                # 同理运用注销功能, 相应的删除该键,即注销成功!
                res.session['user'] = {
                    'username': username,
                    'id': auser.id # 这些数据,记录在当前用户下
                }
                error = "登录成功!"
                
                resp = HttpResponseRedirect('/')
                # 记录复选框按钮, remember 参数在res.POST里面, 说明复选框已被选中
                if 'remember' in res.POST:
                    resp.set_cookie('username', username) # 记录到cookie里,下次登录时会填充用户上次登录的用户名
                    
                # return render(res, 'home/index.html', locals()) # 这条语句也可以
                return resp # 或者用条语句
            error = "账号或者密码错误..."
            return render(res, 'home/login.html', locals())
        
        except Exception as e:
            error = "账号或者密码错误!"
            return render(res, 'home/login.html', locals())
    
def logout_view(res):
    """注销"""
    # 判断session有没有user这个键
    if 'user' in res.session:
        del res.session['user'] # 删除用户session中的记录
        
    return HttpResponseRedirect('/') # 重定向到未登录的主页
  
#%% 手动写的注册代码暂时不用,使用官方用户模板
# def reg_view(res):
#     """注册, 手动写的代码暂时不用"""
#     if res.method == 'GET':
#         return render(res, 'home/register.html')
#     elif res.method == 'POST':
#         username = res.POST.get('username')
#         password = res.POST.get('passwd')
#         password1 = res.POST.get('password1')
#         # 验证数据
#         if len(username) < 6:
#             user_error = "用户名太短!"
#             return render(res, "home/register.html", locals())
#         elif password == '' or password1 == '':
#             if password == '':
#                 password_error = "密码不能为空!"
#                 return render(res, "home/register.html", locals())
#             password1_error = "密码不能为空!"
#             return render(res, "home/register.html", locals())
#         elif password != password1:
#             pass_info = "两次密码不一致"
#             return render(res, "home/register.html", locals())
        
#         try:
#             auser = models.User.objects.get(name=username)
#             # print(auser)
#             if auser != '':
#                 user_error = "用户名已经存在,请换一个吧!"
#                 return render(res, "home/register.html", locals())
#         except Exception as e:
#             auser = models.User.objects.create(name=username, password=password1)
#             pass_info = "注册成功."
#             cookic = HttpResponseRedirect('/')
#             cookic.set_cookie('username', username)
#             return cookic
            
#         return render(res, 'home/login.html')


#%% 官方用户注册模板
def reg_view(res):
    """注册, 手动写的代码暂时不用"""
    if res.method == 'GET':
        return render(res, 'home/register.html')
    elif res.method == 'POST':
        username = res.POST.get('username')
        password = res.POST.get('passwd')
        password1 = res.POST.get('password1')
        # 验证数据
        if len(username) < 6:
            user_error = "用户名太短!"
            return render(res, "home/register.html", locals())
        elif password == '' or password1 == '':
            if password == '':
                password_error = "密码不能为空!"
                return render(res, "home/register.html", locals())
            password1_error = "密码不能为空!"
            return render(res, "home/register.html", locals())
        elif password != password1:
            pass_info = "两次密码不一致"
            return render(res, "home/register.html", locals())
        
        try:
            # django 用户注册模板
            auser = Users.objects.get(username=username)
            # print(auser)
            if auser != '':
                user_error = "用户名已经存在,请换一个吧!"
                return render(res, "home/register.html", locals())
        except Exception as e:
            # 执行注册, create_user为普通用户, create_superuser为创建超级用户
            auser = Users.objects.create_user(username=username, password=password1)
            pass_info = "注册成功."
            cookic = HttpResponseRedirect('/')
            cookic.set_cookie('username', username)
            return cookic
            
        return render(res, 'home/login.html')